﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web.UI.WebControls;
using System.Web.DynamicData;
using System.ComponentModel;
using System.Web.UI;
using System.Web;
using System.Drawing;
using System.Security.Permissions;
using System.Web.Compilation;
using Catalyst.ComponentModel.DataAnnotations;

namespace Catalyst.Web.DynamicData
{
    [DefaultProperty("DataSource")]
    [ParseChildren(true)]
    [AspNetHostingPermission(SecurityAction.InheritanceDemand, Level = AspNetHostingPermissionLevel.Minimal)]
    [AspNetHostingPermission(SecurityAction.Demand, Level = AspNetHostingPermissionLevel.Minimal)]
    [Designer("Catalyst.Web.DynamicData.Design.DynamicFilterRepeaterDesigner, Catalyst.Web.DynamicData.Design")]
    [ToolboxData("<asp:DynamicFilterRepeater runat=\"server\"><HeaderTemplate><div>Search</div></HeaderTemplate><ItemTemplate><div><asp:Label runat=\"server\" Text='<%# Eval(\"DisplayName\") %>' /><asp:DynamicFilterControl runat=\"server\" ID=\"DynamicFilter\" /></div></ItemTemplate><FooterTemplate><div><asp:LinkButton ID=\"SearchButton\" runat=\"server\" Text=\"Search\" CommandName=\"Search\" /><asp:LinkButton ID=\"ClearButton\" runat=\"server\" Text=\"Clear\" CommandName=\"Clear\" /></div></FooterTemplate></asp:DynamicFilterRepeater>")]
    [ToolboxBitmap(typeof(DynamicFilterRepeater))]
    public class DynamicFilterRepeater : DynamicFilterContainerBase, IWhereParametersProvider
    {
        private Repeater _repeater;

        public DynamicFilterRepeater()
        {
            _repeater = new Repeater();
            _repeater.ItemCreated += new RepeaterItemEventHandler(FilterItemCreated);
            _repeater.ItemCommand += new RepeaterCommandEventHandler(ItemCommand);
        }

        [Browsable(false)]
        [PersistenceMode(PersistenceMode.InnerProperty)]
        [DefaultValue(typeof(FilterTemplate), "")]
        [Description("Filter Item Template")]
        public ITemplate ItemTemplate
        {
            get { return _repeater.ItemTemplate; }
            set { _repeater.ItemTemplate = value; }
        }

        [Browsable(false)]
        [PersistenceMode(PersistenceMode.InnerProperty)]
        [DefaultValue(typeof(FilterTemplate), "")]
        [Description("Header Template")]
        public ITemplate HeaderTemplate
        {
            get { return _repeater.HeaderTemplate; }
            set { _repeater.HeaderTemplate = value; }
        }

        [Browsable(false)]
        [PersistenceMode(PersistenceMode.InnerProperty)]
        [DefaultValue(typeof(FilterTemplate), "")]
        [Description("Footer Template")]
        public ITemplate FooterTemplate
        {
            get { return _repeater.FooterTemplate; }
            set { _repeater.FooterTemplate = value; }
        }

        protected override void CreateChildControls()
        {
            this.Controls.Add(_repeater);
        }

        private MetaTable GetTable()
        {
            IPredicateDynamicDataSource dataSource = this.PredicateDynamicDataSource;
            if (dataSource == null)
                throw new InvalidOperationException("Missing DataSource");

            return dataSource.GetTable();
        }

        public object GetFilters()
        {
            MetaTable table = GetTable();
            if (table == null)
                throw new InvalidOperationException("Could not load table");

            List<MetaColumn> filterColumns = new List<MetaColumn>();
            foreach (MetaColumn mc in table.Columns)
            {
                foreach (Attribute attribute in mc.Attributes)
                {
                    if (attribute is FilterAttribute)
                    {
                        filterColumns.Add(mc);
                        break;
                    }
                }
            }
            return filterColumns;
        }

        protected override void OnInit(EventArgs e)
        {
            base.OnInit(e);
            if (base.DesignMode)
                return;
            
            _repeater.DataSource = GetFilters();
            _repeater.DataBind();
            
        }

        private void CreateFilterItem(RepeaterItem item)
        {
            DynamicFilterControl control = item.FindControl("DynamicFilter") as DynamicFilterControl;
            if (control == null)
            {
                throw new InvalidOperationException(string.Format("Could not find {0} in template", "DynamicFilter"));
            }
            MetaColumn mc = (MetaColumn)item.DataItem;
            control.Column = mc;
            FilterAttribute attribute = ((FilterAttribute)mc.Attributes[typeof(FilterAttribute)]);
            control.FilterMode = attribute.FilterMode;
            control.UIHint = attribute.UIHint;
        }

        private void FilterItemCreated(object sender, RepeaterItemEventArgs e)
        {
            if (!base.DesignMode)
            {
                switch (e.Item.ItemType)
                {
                    case ListItemType.Item:
                    case ListItemType.AlternatingItem:
                        CreateFilterItem(e.Item);
                        break;
                }
            }
        }

        private void ItemCommand(object source, RepeaterCommandEventArgs e)
        {
            OnBubbleEvent(source, e);
        }

    }

}
